package cross;

import individuals.Individual;

import java.util.ArrayList;
import java.util.List;

public class SegmentedCross implements Cross{
	private double percent;
	
	public SegmentedCross(double percent) {
		this.percent =  percent;
		if(percent>1 || percent <=0)
			throw new RuntimeException("El porcentaje en SegmentedCross debe ser mayor a 0 o menor igual a 1");
	}
	
	public List<Individual> Apply(Individual father, Individual mother) {
		List<Individual> list = new ArrayList<Individual>();
		long mask = 0;
		
		for(int i=0; i<64; i++) {
			mask<<=1;
			if(Cross.ranGen.nextDouble()<percent)
				mask+=1;
		}
		
		long mask1 = mask;
		long mask2 = mask;
		
		mask1 &= Double.doubleToRawLongBits(father.getGen());
		mask2 &= Double.doubleToRawLongBits(mother.getGen());
		
		mask = ~mask;
		Double son1 = Double.longBitsToDouble((Double.doubleToRawLongBits(father.getGen())&mask)|mask2);
		Double son2 = Double.longBitsToDouble((Double.doubleToRawLongBits(mother.getGen())&mask)|mask1);
		list.add(new Individual(son1));
		list.add(new Individual(son2));
		
		return list;
	}
}
